package com.sm.healthy.utils

import java.util.*

/**
 * @description
 * @author csw
 * @date 2022-05-05
 */
object CalendarUtil {
    fun curWeek(): Int = Calendar.getInstance(Locale.GERMANY).get(Calendar.WEEK_OF_MONTH)
    fun curMonth(): Int = Calendar.getInstance(Locale.GERMANY).get(Calendar.MONTH)

    fun weekStart(weekOfMonth: Int) = weekDay(Calendar.MONDAY, weekOfMonth).let {
        it.startTime()
        it.timeInMillis
    }

    fun weekEnd(weekOfMonth: Int) = weekDay(Calendar.SUNDAY, weekOfMonth).let {
        it.endTime()
        it.timeInMillis
    }

    fun monthStart(month: Int) = monthDay(month = month).let {
        it.startTime()
        it.timeInMillis
    }

    fun monthEnd(month: Int) = monthDay(month = month + 1).let {
        it.add(Calendar.DATE, -1)
        it.endTime()
        it.timeInMillis
    }

    private fun weekDay(day: Int, weekOfMonth: Int): Calendar {
        val calendar = Calendar.getInstance(Locale.GERMANY)
        calendar.set(Calendar.WEEK_OF_MONTH, weekOfMonth)
        calendar.set(Calendar.DAY_OF_WEEK, day)
        return calendar
    }

    private fun monthDay(day: Int = 1, month: Int): Calendar {
        val calendar = Calendar.getInstance(Locale.GERMANY)
        calendar.set(Calendar.MONTH, month)
        calendar.set(Calendar.DAY_OF_MONTH, day)
        return calendar
    }

    private fun Calendar.startTime() {
        set(Calendar.HOUR_OF_DAY, 0)// H置零
        set(Calendar.MINUTE, 0)// m置零
        set(Calendar.SECOND, 0)// s置零
        set(Calendar.MILLISECOND, 0)// S置零
    }

    private fun Calendar.endTime() {
        set(Calendar.HOUR_OF_DAY, 23)// H置零
        set(Calendar.MINUTE, 59)// m置零
        set(Calendar.SECOND, 59)// s置零
    }
}